package iagovsothello.online.server;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.SocketTimeoutException;

public class UDPListener extends Thread {

	private String serverAddress;
	private int serverPort;
	private String broadcastAddress;
	private int broadcastPort;
	private boolean running;
	
	public UDPListener(String serverAddress, int serverPort, String broadcastAddress, int broadcastPort) 
	{
		super();
		this.serverAddress = serverAddress;
		this.serverPort = serverPort;
		this.broadcastAddress = broadcastAddress;
		this.broadcastPort = broadcastPort;
	}
	
	public synchronized void setRunning(boolean running)
	{
		this.running = running;
	}
	
	public synchronized boolean isRunning()
	{
		return running;
	}
	
	public void run()
	{
		setRunning(true);
		MulticastSocket socket = null;
		try {
			//creazione socket
			InetAddress address = InetAddress.getByName(broadcastAddress);
			socket = new MulticastSocket(broadcastPort);
			socket.joinGroup(address);
			socket.setTimeToLive(1);
			socket.setSoTimeout(5000);
			
			//attesa richiesta
			byte[] inputBuffer = new byte[1024];
			while(isRunning())
			{
				DatagramPacket inputPacket = new DatagramPacket(inputBuffer, inputBuffer.length);
				try {
					socket.receive(inputPacket);
					BufferedReader in = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(inputBuffer), "UTF-8"));
					if (in.readLine().equals("request address"))
					{
						//creazione messaggio di risposta
						ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
						PrintWriter out = new PrintWriter(new OutputStreamWriter(bos,"UTF-8"));
						out.println("server address");
						out.println(serverAddress);
						out.println(serverPort);
						out.flush();

						//invio messaggio
						byte buffer[] = bos.toByteArray();
						DatagramPacket packet = new DatagramPacket(buffer,buffer.length,address,broadcastPort);
						socket.send(packet);
					}
				} catch (SocketTimeoutException e) { }
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		if (socket != null)
		{
			socket.close();
		}
	}
}
